//
//  String_Ex.swift
//  Dawn
//
//  Created by cuicheng on 2021/9/6.
//

import UIKit

public extension String {
    var url: URL? {
        return URL(string: self)
    }
    
    var hostUrl: URL? {
        guard let url = url else { return nil }
        return String(prefix(count - url.relativePath.count)).url
    }
    
    var fileUrl: URL? {
        return URL(fileURLWithPath: self)
    }
    
    var image: UIImage? {
        return UIImage(named: self)
    }
    
    func size(font: UIFont,
              maxSize: CGSize) -> CGSize {
        let attributes = [NSAttributedString.Key.font: font ]
        let options: NSStringDrawingOptions = [.usesFontLeading,
                                               .usesLineFragmentOrigin]
        let textSize = self.boundingRect(with: maxSize,
                                     options: options,
                                     attributes: attributes,
                                     context: nil).size
        return CGSize(width: ceil(textSize.width),
                      height: ceil(textSize.height))
    }
    
    func height(font: UIFont,
                maxWidth: CGFloat) -> CGFloat {
        return size(font: font, maxSize: CGSize(width: maxWidth, height: CGFloat.greatestFiniteMagnitude)).height
    }

    /// 字符串截取 闭区间截取
    /// - Parameters:
    ///   - start: 起始位置
    ///   - end: 结束位置
    /// - Returns: 截取后字符串
    func sub(from start: Int,
             to end: Int) -> String {
        if start > end { return "" }
        let start = max(0, start)
        let end = min(count, end)
        let fromIndex = self.index(startIndex, offsetBy: start)
        let toIndex = self.index(startIndex, offsetBy: end)
        return String(self[fromIndex..<toIndex])
    }
    
    func insert(_ str: String, location: Int)-> String {
        let _text = NSMutableString(string: self)
        _text.insert(str, at: location)
        return _text as String
    }
    
    func remove(_ range: NSRange)-> String {
        let _text = NSMutableString(string: self)
        _text.replaceCharacters(in: range, with: "")
        return _text as String
    }
    
    ///当前位置字符
    func letter(of index: Int) -> String {
        if index >= count {
            return ""
        }
        return String(self.prefix(index+1).last!)
    }
    
    /*
     *去掉首尾空格
     */
    var removeHeadAndTailSpace:String {
        let whitespace = NSCharacterSet.whitespaces
        return self.trimmingCharacters(in: whitespace)
    }
    /*
     *去掉首尾空格 包括后面的换行 \n
     */
    var removeHeadAndTailSpacePro:String {
        let whitespace = NSCharacterSet.whitespacesAndNewlines
        return self.trimmingCharacters(in: whitespace)
    }
    /*
     *去掉所有空格
     */
    var removeAllSapce: String {
        return self.replacingOccurrences(of: " ", with: "", options: .literal, range: nil)
    }
    /*
     *去掉首尾空格 后 指定开头空格数
     */
    func beginSpaceNum(num: Int) -> String {
        var beginSpace = ""
        for _ in 0..<num {
            beginSpace += " "
        }
        return beginSpace + self.removeHeadAndTailSpacePro
    }
    
    func text(font: UIFont, color: UIColor) -> NSMutableAttributedString {
        let text = NSMutableAttributedString(string: self)
        text.yy_font = font
        text.yy_color = color
        return text
    }
    
    func iconText(fontSize: CGFloat, color: UIColor) -> NSMutableAttributedString {
        let text = NSMutableAttributedString(string: self)
        text.yy_font = UIFont(name: "baseIcon", size: fontSize)
        text.yy_color = color
        return text
    }
}

public extension NSAttributedString {
    func size(maxSize:
                CGSize) -> CGSize {
        let options: NSStringDrawingOptions = [.truncatesLastVisibleLine,
                                               .usesLineFragmentOrigin]
        let textSize = self.boundingRect(with: maxSize,
                                         options: options,
                                         context: nil).size
        return CGSize(width: ceil(textSize.width),
                      height: ceil(textSize.height))
    }
    
    func height(maxWidth: CGFloat, maxHeight: CGFloat = CGFloat.greatestFiniteMagnitude) -> CGFloat {
        return size(maxSize: CGSize(width: maxWidth, height: maxHeight)).height
    }
    
}

public extension NSMutableAttributedString {
    func added(_ text: NSAttributedString) -> NSMutableAttributedString {
        append(text)
        return self
    }
}
